package com.crowdgeeks.controller;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

import com.crowdgeeks.model.User;
import com.crowdgeeks.util.PMF;

@Controller
public class HomeController {
    private Log log = LogFactory.getLog(HomeController.class);

    private String consumerKey = "zVmhNcjLILJromtPDLIs9Q";

    private String consumerSecret = "XgcuTJegqIAnsRUHreJZd2C7ICW7xqBnzqLrDgPffA";

    @RequestMapping(value = "/index")
    public String root() {
        log.debug("redirect home");

        return "twitter/index";
    }

    @RequestMapping(value = "/user/list")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        log.debug("list");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        //String query = "select from " + User.class.getName();

        List<User> userList = null;
        try {
            userList = (List<User>) pm.newQuery(User.class).execute();
        } catch (Exception e) {
            log.error(e, e);
        }

        request.setAttribute("userList", userList);

        return "user/list";
    }

    @RequestMapping(value = "/user/delete")
    public String delete(HttpServletRequest request, HttpServletResponse response) {
        log.debug("delete");

        String id = request.getParameter("id");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            User user = pm.getObjectById(User.class, id);
            pm.deletePersistent(user);
        } finally {
            pm.close();
        }

        return "redirect:/user/list";
    }

    @RequestMapping(value = "/user/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        log.debug("logout");

        String id = request.getParameter("id");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            User user = pm.getObjectById(User.class, id);

            AccessToken accessToken = new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret());
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(consumerKey, consumerSecret);

            twitter.setOAuthAccessToken(accessToken);

            twitter.shutdown();
        } catch (Exception e) {
            log.error(e, e);
        } finally {
            pm.close();
        }

        return "redirect:/user/list";
    }
}
